﻿; Script settings
#SingleInstance force
#UseHook On
SetTitleMatchMode 2

; Check and retrieve params
if 0 < 2
{
    MsgBox Usage: Runner.exe "System Name" "Rom Name"
    ExitApp
}
systemName = %1%
romName = %2%

; Global settings
g_exitEmulatorKey = Esc
g_cfgDir = %A_ScriptDir%\config
g_emuDir = %A_ScriptDir%\emulators
g_romDir = %A_ScriptDir%\romfiles\%systemName%
g_emuIni = %g_cfgDir%\%systemName%.ini

IfNotExist, %g_emuIni%
{
	MsgBox %g_emuIni% "does not exist"
	ExitApp
}

; INI settings
IniRead, s_emuExe, %g_emuIni%, emulator, exe
IniRead, s_emuPath, %g_emuIni%, emulator, path
IniRead, s_emuParams, %g_emuIni%, emulator, params
IniRead, s_useRomFullPath, %g_emuIni%, emulator, fullrompath
IniRead, s_enableExitKey, %g_emuIni%, emulator, enableexitkey
IniRead, s_romExtensions, %g_emuIni%, roms, extensions

; Check ROM path
Loop, parse, s_romExtensions, `,
{
	IfExist, %g_romDir%\%romName%.%A_LoopField%
		romFullPath = %g_romDir%\%romName%.%A_LoopField%
}
if (romFullPath = "")
{
	MsgBox "Could not find ROM file"
	ExitApp
}

; Building command line
cmdExe = %g_emuDir%\%s_emuPath%\%s_emuExe%
cmdParams = %s_emuParams%
if (s_useRomFullPath = "true")
{
	StringReplace, cmdParams, cmdParams, $ROM$, %romFullPath%
}
else
{
	StringReplace, cmdParams, cmdParams, $ROM$, %romName%
}

; Running the emulator
if (s_enableExitKey = "true")
{
	Hotkey, %g_exitEmulatorKey%, CloseProcess, On
}
Run, %cmdExe% %cmdParams%, %g_emuDir%\%s_emuPath%
Process, WaitClose, %s_emuExe%
Goto ExitScript

; Callback when the exit emulator key is pressed
CloseProcess:
if (s_enableExitKey = "true")
{
	Hotkey, %g_exitEmulatorKey%, Off
}
Process, Close, %s_emuExe%
Process, WaitClose, %s_emuExe%
return

; Callback when exiting the script
ExitScript:
Gui, destroy
ExitApp

OnExit, ExitScript
return